package com.android.infantschool.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.infantschool.R;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.QiNiuTokenBean;
import com.android.infantschool.bean.ReleaseDynamicBean;
import com.android.infantschool.bean.ResponseBean;
import com.android.infantschool.manager.ThreadPoolManager;
import com.android.infantschool.model.config.AppCommand;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.config.AppDataSource;
import com.android.infantschool.model.http.OkHttpUtil;
import com.android.infantschool.model.mvp.presenter.ReleaseDynamicPresenter;
import com.android.infantschool.model.mvp.presenter.ReleaseDynamicPresenterImpl;
import com.android.infantschool.model.mvp.view.ReleaseDynamicView;
import com.android.infantschool.model.qiniu.QnUploadHelper;
import com.android.infantschool.ui.adapter.ReleaseDynamicAdapter;
import com.android.infantschool.util.Constant;
import com.android.infantschool.util.JsonGet;
import com.android.infantschool.util.ScreenUtil;
import com.android.infantschool.util.ToastUtil;
import com.qiniu.android.http.ResponseInfo;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Administrator
 * @particulars
 * @time 2019\7\5 0005 15:52
 * @class describe
 */
public class ReleaseDynamicActivity extends BaseActivity implements ReleaseDynamicAdapter.OnImgLister, ReleaseDynamicView {

    @BindView(R.id.img_back)
    public ImageView imgBack;
    @BindView(R.id.title)
    public RelativeLayout rlTitle;
    @BindView(R.id.tv_title)
    public TextView tvTitle;
    @BindView(R.id.ed_content)
    public EditText edContent;
    @BindView(R.id.tv_content_size)
    public TextView tvContentSize;
    @BindView(R.id.recyclerView)
    public RecyclerView recyclerView;
    @BindView(R.id.btn_release)
    public Button btnRelease;

    public ReleaseDynamicAdapter adapter;
    private ReleaseDynamicPresenter dynamicPresenter = null;
    private List<ReleaseDynamicBean> list = null;

    private JSONArray jsonArray = new JSONArray();
    private JSONObject jsonObject = null;

    private int REQUEST_GET_IMAGE = 1;

    //存放图片或视频路径的ArrayList
    private int picNum = 0;                 //当前上传到多少张
    private boolean flag = true;            //true:上传结束,false:正在上传

    public static Intent newIntent(Activity activity, List<ReleaseDynamicBean> list) {
        Intent intent = new Intent(activity, ReleaseDynamicActivity.class);
        intent.putExtra("list", (Serializable) list);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_dynamic);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        dynamicPresenter = new ReleaseDynamicPresenterImpl(this);
        rlTitle.setPadding(0, this.height, 0, 0);
        tvTitle.setText("发布动态");

        list = (List<ReleaseDynamicBean>) getIntent().getSerializableExtra("list");

        adapter = new ReleaseDynamicAdapter(this, this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5) {
            @Override
            public boolean canScrollVertically() {
                return false;//禁止滑动
            }
        };
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setData(AppDataSource.getReleaseDynamicList());

        if (this.list != null) {
            if (this.list.size() > 0) {
                adapter.addAllData(this.list);
            }
        }

        edContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int length = s.toString().length();
                length = 200 - length;
                tvContentSize.setText(length + "/200");
            }
        });
    }

    @OnClick({R.id.btn_release, R.id.img_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_release:
                String content = edContent.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    ToastUtil.showShortToast(this, "请输入发布内容");
                    return;
                }

                if (adapter.list.size() < 2) {
                    ToastUtil.showShortToast(this, "请选择图片");
                    return;
                }

                if (flag == true) {
                    this.showLoading();
                    qiuNiuYunToKen((String) adapter.list.get(picNum).path, String.valueOf(adapter.list.get(picNum).type), adapter.getItemCount() - 1);
                    flag = false;
                } else {
                    Toast.makeText(this, "正在上传，请稍后...", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.img_back:
                this.finish();
                break;
        }
    }

    private Runnable runnable = null;

    /**
     * 上传到七牛
     *
     * @param picUrl
     * @param picSize
     */
    private void qiuNiuYunToKen(final String picUrl, final String type, final int picSize) {
        runnable = new Runnable() {
            @Override
            public void run() {

                String qiNiuToken = OkHttpUtil.getmInstance().postSync(AppCommand.QINIU_TOKEN, "token", AppConfig.getToken());

                Log.e(TAG, "qiNiuToken:" + qiNiuToken);
                if (qiNiuToken != null) {
                    QiNiuTokenBean tokenBean = null;
                    try {
                        tokenBean = JsonGet.getGson(qiNiuToken, new QiNiuTokenBean());
                    } catch (Exception e) {
                        e.toString();
                        tokenBean = null;
                    }

                    if (tokenBean == null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                picNum = 0;
                                flag = true;
                                ReleaseDynamicActivity.this.dismissLoading();
                                ToastUtil.showShortToast(ReleaseDynamicActivity.this, "网络异常,请稍后再试!");
                            }
                        });
                        return;
                    }

                    if (tokenBean.getCode().equals("0")) {//Token获取成功
                        Log.e(TAG, "qiNiuToken:" + tokenBean.getData().getToken());
                        String ceshitoken = tokenBean.getData().getToken();//请求完接口获取到的token值
                        String key = tokenBean.getData().getKey();
                        Log.e(TAG, "++++++++ceshitoken:" + ceshitoken);
                        // return qiNiuYunBean.getToken();
                        Log.e(TAG, "++++++picNum=" + picNum);
                        Log.e(TAG, "++++++picSize=" + picSize);
                        Log.e(TAG, "++++++picUrl=" + picUrl);

                        QnUploadHelper.uploadPic(picUrl, key, ceshitoken, new QnUploadHelper.UploadCallBack() {
                            @Override
                            public void success(String url) {
                                Log.e(TAG, "上传七牛成功:" + url);
                                picNum++;
                                jsonObject = new JSONObject();
                                try {
                                    jsonObject.put("type", type);
                                    jsonObject.put("path", url);
                                    jsonArray.put(jsonObject);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                if (picNum < picSize) {
                                    qiuNiuYunToKen((String) adapter.list.get(picNum).path, String.valueOf(adapter.list.get(picNum).type), picSize);
                                } else {
                                    picNum = 0;
                                    flag = true;
                                    Log.e(TAG, "上传完毕");
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", AppConfig.getToken());
                                    map.put("url", jsonArray.toString());
                                    map.put("content", edContent.getText().toString().trim());
                                    Log.e(TAG, "map:" + map.toString());
                                    dynamicPresenter.postReleaseDynamic(map);
                                    return;
                                }
                            }

                            @Override
                            public void fail(String key, ResponseInfo info) {
                                Log.e(TAG, "上传失败:" + info.error);
                                picNum++;
                                if (picNum < picSize) {
                                    qiuNiuYunToKen((String) adapter.list.get(picNum).path, String.valueOf(adapter.list.get(picNum).type), picSize);
                                } else {
                                    picNum = 0;
                                    flag = true;
                                    Log.e(TAG, "上传完毕");
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", AppConfig.getToken());
                                    map.put("url", jsonArray.toString());
                                    map.put("content", edContent.getText().toString().trim());
                                    Log.e(TAG, "map:" + map.toString());
                                    dynamicPresenter.postReleaseDynamic(map);
                                    return;
                                }
                            }
                        });
                    } else {
                        Log.e(TAG, "Token获取失败:" + tokenBean.getMsg());
                        final QiNiuTokenBean finalTokenBean = tokenBean;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                picNum = 0;
                                flag = true;
                                ReleaseDynamicActivity.this.dismissLoading();
                                ToastUtil.showShortToast(ReleaseDynamicActivity.this, "Token获取失败:" + finalTokenBean.getMsg());
                            }
                        });
                    }
                } else {
                    Log.e(TAG, "接口异常或网络异常");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            picNum = 0;
                            flag = true;
                            ReleaseDynamicActivity.this.dismissLoading();
                            ToastUtil.showShortToast(ReleaseDynamicActivity.this, "网络异常或接口发生异常");
                        }
                    });
                }
            }
        };
        ThreadPoolManager.getSingleInstance().execute(runnable);
    }

    /**
     * 跳转到相册页
     */
    private void startCameta() {

        //1、第一种方法,系统默认
        /*Intent picture = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(picture, REQUEST_GET_IMAGE);*/

        //2、第二种方法,第三方库
        Matisse.from(this)
                .choose(MimeType.ofAll(), false) // 选择 mime 的类型
                .countable(true)
                .capture(false)
                .captureStrategy(new CaptureStrategy(true, "com.android.infantschool.fileprovider"))
                .maxSelectable(9) // 图片选择的最多数量
                .gridExpectedSize(ScreenUtil.getWidth() / 3)
                .theme(R.style.Matisse_Dracula)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_GET_IMAGE); // 设置作为标记的请求码
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_GET_IMAGE && resultCode == Activity.RESULT_OK && null != data) {

            //1、第一种方法,系统默认
            List<String> pathList = Matisse.obtainPathResult(data);
            Log.e(TAG, "pathList:" + Arrays.toString(pathList.toArray()));
            for (int index = 0; index < pathList.size(); index++) {
                if (adapter.getItemCount() < 10) {
                    if (pathList.get(index).endsWith(".AVI") || pathList.get(index).endsWith(".mov") || pathList.get(index).endsWith(".rmvb") || pathList.get(index).endsWith(".rm") ||
                            pathList.get(index).endsWith(".FLV") || pathList.get(index).endsWith(".mp4") || pathList.get(index).endsWith(".3GP")) {
                        adapter.addData(new ReleaseDynamicBean(pathList.get(index), 2));
                    } else {
                        adapter.addData(new ReleaseDynamicBean(pathList.get(index), 1));
                    }
                } else {
                    break;
                }
            }

            //2、第二种方法,第三方库
            /*Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String picturePath = c.getString(columnIndex);
            Log.e(TAG, "图片路径:" + picturePath);
            c.close();
            if (adapter.getItemCount() < 10) {
                adapter.addData(new ReleaseDynamicBean(picturePath, 1));
            } else {
                ToastUtil.showShortToast(this, "上传照片数量最大只能为9张");
            }*/
        }
    }

    @Override
    public void errorReleaseDynamic(String error) {
        picNum = 0;
        flag = true;
        ReleaseDynamicActivity.this.dismissLoading();
        ToastUtil.showShortToast(ReleaseDynamicActivity.this, "网络异常:" + error);
    }

    @Override
    public void successReleaseDynamic(BaseBean baseBean) {
        this.dismissLoading();
        picNum = 0;
        flag = true;
        ResponseBean responseBean = (ResponseBean) baseBean;
        if (responseBean.getCode() == 0) {
            ToastUtil.showShortToast(ReleaseDynamicActivity.this, "发布成功");
            this.finish();
        } else {
            ToastUtil.showShortToast(ReleaseDynamicActivity.this, "发布失败:" + responseBean.getMsg());
        }
    }

    @Override
    public void imgLister(int position, int type) {
        if (position == (adapter.getItemCount() - 1)) {//去拍照
            startCameta();
        } else {    //去预览

        }
    }

    @Override
    public void deleteLister(int position, int type) {
        adapter.deleteItem(position);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause...");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume..." + flag);
        if (flag == false) {
            this.showLoading();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dynamicPresenter != null) {
            dynamicPresenter.onDestroy();
            dynamicPresenter = null;
        }
        if (runnable != null) {
            ThreadPoolManager.getSingleInstance().remove(runnable);
        }
    }

}